#!/usr/bin/python

import os
import sys
import subprocess

# And now move it to function for reusable

AESPIPE    = "/usr/bin/aespipe"
PASSPHRASE = "./passphrase.txt"
BASE64     = "/usr/bin/base64"
cryptcmd   = [ AESPIPE, "-P", PASSPHRASE ]
decryptcmd = [ AESPIPE, "-P", PASSPHRASE , "-d" ]
encodecmd  = [ BASE64 ]
decodecmd  = [ BASE64, "--decode" ]

# ---------------------------------------------------------------------
#
# ---------------------------------------------------------------------
def	pipe(cmd, buf):
	p = subprocess.Popen(	cmd,
				bufsize=0,
				stdin=subprocess.PIPE,
				stdout=subprocess.PIPE)

	p.stdin.write(buf)
	return p.communicate()[0]

# ---------------------------------------------------------------------
# Encrypt message
# ---------------------------------------------------------------------
def	crypt(buf):
	return pipe(cryptcmd, buf)

# ---------------------------------------------------------------------
# Decrypt message
# ---------------------------------------------------------------------
def	decrypt(buf):
	return pipe(decryptcmd, buf)

# ---------------------------------------------------------------------
# Encode message
# ---------------------------------------------------------------------
def	encode(buf):
	return pipe(encodecmd, buf)

# ---------------------------------------------------------------------
# Decode message
# ---------------------------------------------------------------------
def	decode(buf):
	return pipe(decodecmd, buf)

# ---------------------------------------------------------------------
# Main program
# ---------------------------------------------------------------------

if len(sys.argv) <> 3:
	print "Usage: %s input output" % sys.argv[0]
	exit(0)

input = sys.argv[1]
output = sys.argv[2]

if not os.path.exists(PASSPHRASE):
	print "passphrase file '%s' not exists" % PASSPHRASE
	exit(0)

if not os.path.exists(input):
	print "input file '%s' not exists" % input
	exit(0)

if os.path.exists(output):
	print "output file '%s' already exists, please remove it first" % output
	exit(0)
try:
	f1 = open(input, 'r')
except IOError:
	print "Can't open file '%s'" % input
	exit(0)

try:
	f2 = open(output, 'w')
except IOError:
	print "Can't create output file '%s'" % output
	exit(0)

buf = f1.read()
l = len(buf)
print "Read %d bytes from %s" % (l, input)

if l > (1024*100):
	print "Input file is too big, bail out!"
	exit(0)

cmesg = encode(crypt(buf))
dmesg = decrypt(decode(cmesg))

print "buf   = ", buf
print "cmesg = ", cmesg
print "dmesg = ", dmesg

f2.write(dmesg)
print "Done."
exit(0)
